package com.springboot.killingsystem.controller;

import com.springboot.killingsystem.domain.SecondKillingUser;
import com.springboot.killingsystem.redis.GoodsKey;
import com.springboot.killingsystem.redis.RedisService;
import com.springboot.killingsystem.result.Result;
import com.springboot.killingsystem.service.GoodsService;
import com.springboot.killingsystem.service.SecondKillingUserService;
import com.springboot.killingsystem.util.Constant;
import com.springboot.killingsystem.vo.GoodsDetailVo;
import com.springboot.killingsystem.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    RedisService redisService;

    @Autowired
    SecondKillingUserService secondKillingUserService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 使用页面缓存之前：QPS 2784.7（5000*10，硬件：8核16线程，16G内存）
     * 使用页面缓存之后：QPS 8523.7（5000*10，硬件：8核16线程，16G内存）
     */
    @RequestMapping(value = "/to_list", produces = "text/html")
    @ResponseBody
    public String toList(
            HttpServletRequest request,
            HttpServletResponse response,
            Model model,
            SecondKillingUser user
    ) {
        model.addAttribute(Constant.USER, user);
        String html = redisService.get(GoodsKey.getGoodsList, Constant.DEFAULT_KEY, String.class);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }

        // 查询商品
        List<GoodsVo> goodsList = goodsService.getGoodsVoList();
        model.addAttribute(Constant.GOODS_VO_LIST, goodsList);
//        return "goods_list";

        // 手动渲染
        WebContext wc = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process(Constant.GOODS_LIST, wc);
        if (!StringUtils.isEmpty(html)) {
            redisService.set(GoodsKey.getGoodsList, Constant.DEFAULT_KEY, html);
        }

        return html;
    }

    @RequestMapping(value = "/detail/{goodsId}")
    @ResponseBody
    public Result<GoodsDetailVo> toDetail(
            SecondKillingUser user,
            @PathVariable("goodsId") long goodsId
    ) {
        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);

        long startAt = goods.getStartDate().getTime();
        long endAt = goods.getEndDate().getTime();
        long now = System.currentTimeMillis();

        int secondKillingStatus;
        int remainSeconds;

        if (now < startAt) { // 秒杀未开始,倒计时
            secondKillingStatus = 0;
            remainSeconds = (int) (startAt - now) / 1000;
        }else if (now > endAt) { // 秒杀已结束
            secondKillingStatus = 2;
            remainSeconds = -1;
        }else { // 秒杀进行时
            secondKillingStatus = 1;
            remainSeconds = 0;
        }

        goodsDetailVo.setGoods(goods);
        goodsDetailVo.setUser(user);
        goodsDetailVo.setSecondKillingStatus(secondKillingStatus);
        goodsDetailVo.setRemainSeconds(remainSeconds);

        return Result.success(goodsDetailVo);
    }
}
